package com.lz.sports.widget

import android.animation.ValueAnimator
import android.animation.ValueAnimator.AnimatorUpdateListener
import android.content.Context
import android.util.AttributeSet
import android.widget.LinearLayout

class ExpandLinearLayout : LinearLayout {
    //初始高度
    private var initHeight = 0
    //动画
    private var anim: ValueAnimator? = null
    //动画回调
    private val animListener by lazy {
        AnimatorUpdateListener {
            val params = layoutParams
            val size = it.animatedValue as Int
            params.height = size
            layoutParams = params
        }
    }
    //是否为展开
    var isExpand = true
        private set

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        anim?.cancel()
    }

    fun select() {
        if (isExpand) collapse() else expand()
    }

    private fun expand() {
        anim?.cancel()
        anim = ValueAnimator.ofInt(0, initHeight).apply { addUpdateListener(animListener) }
        anim?.start()
        isExpand = true
    }

    private fun collapse() {
        anim?.cancel()
        initHeight = height
        anim = ValueAnimator.ofInt(initHeight, 0).apply { addUpdateListener(animListener) }
        anim?.start()
        isExpand = false
    }
}